// pages/container/order-details/activity-to-pay/activity-to-pay.js
const app = getApp();
const tool = require("../../../../utils/util.js");
const server = require("../../../../utils/server.js");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isIPhoneX: app.globalData.isIPhoneX,
    payMethod: "weixin",
    pageShow: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    const _this = this;
    app.getLoadData().then(function(res) {
      console.log(res)
      _this.setData({
        userInfo: res.data
      });
      _this.loadPage(options);
    })
  },
  loadPage: function(options) {
    const _this = this;
    const param = {
      member_id: _this.data.userInfo.member_id,
      all_no: options.all_no,
      order_label: options.order_label
    };
    server.postJSON("/index/order/order_info", param, function(res) {
      if (res.data.error != 0) {
        tool.warning(res.data.message);
        return;
      }
      var item_num = 0;
      for (var i = 0; i < res.data.data.goods_list.length; i++) {
        if (res.data.data.order_label == 4) {
          res.data.data.tpl_name = "custom_order";
          res.data.data.attend_time = tool.formatDate(new Date(res.data.data.customized_time * 1000), 'yyyy年mm月dd日 hh:ii');
          
        } else {
          res.data.data.tpl_name = "activity_order";
          res.data.data.goods_list[i].attend_time = tool.formatDate(new Date(res.data.data.goods_list[i].activity.ua_start_time * 1000), 'yyyy-mm-dd');
        }
        item_num += res.data.data.goods_list[i].item_num;
      }
      if(res.data.data.order_label == 4) {
        var payedMoney = 0;
        // 计算已经支付金额
        for(var i = 0; i < res.data.data.pay_log.length; i++) {
          payedMoney += (res.data.data.pay_log[i].pay_money * 100)
        }
        payedMoney = payedMoney / 100;
        res.data.data.payedMoney = payedMoney ;
        // 获取待支付金额
        if (res.data.data.project == '预付款') {
          res.data.data.topayMoney = res.data.data.deposit
        } else {
          res.data.data.topayMoney = res.data.data.order_amount - payedMoney
        }
      } else {
        res.data.data.topayMoney = res.data.data.order_amount
      }
      res.data.data.item_num = item_num;
      res.data.data.unit_price = res.data.data.order_amount / item_num;
      res.data.data.total_price = res.data.data.order_amount;
      _this.setData({
        pageShow: true,
        confirmData: res.data.data
      });
      _this.getServerInfo({
        ser_id: res.data.data.ser_id
      })
    });
  },
  getServerInfo: function(options) {
    const _this = this;
    server.postJSON('/index/chat/ser_info', options, function(res) {
      if (res.data.error != 0) {
        tool.warning(res.data.message);
        return
      }
      _this.setData({
        serverInfo: res.data.data
      })
    })
  },
  /**
   * 是否使用钱包支付
   */
  switchChange: function(e) {
    const _this = this;
    var isWalletPay = e.detail.value;
    if (_this.data.confirmData.available_predeposit <= 0) {
      isWalletPay = false;
    }
    this.setData({
      isWalletPay: isWalletPay
    })
  },
  /**
   * 选择付款方式
   */
  choosePayMethod: function(e) {
    const _this = this;
    const payMethod = e.currentTarget.dataset.payMethod;
    if (payMethod !== _this.data.payMethod) {
      _this.setData({
        payMethod: payMethod
      });
    }
  },
  // 调起支付
  topay: function() {
    const _this = this;
    const confirmData = _this.data.confirmData;
    console.log(typeof confirmData.order_label)
    if (confirmData.order_label == 4) {
    // return
      if (_this.data.payMethod === 'duigong' || _this.data.payMethod === 'xianjin' ) {
        _this.toCorporate.show();
        return
      }
    }

    const param = {
      all_no: _this.data.confirmData.all_no,
      order_label: _this.data.confirmData.order_label,
      openid: _this.data.userInfo.openid
    }
    if (_this.data.isWalletPay) {
      param.is_wallet = 2;
      wx.showModal({
        title: '提示',
        content: '确定使用钱包支付',
        success: function(res){
          console.log(res)
          if(res.confirm) {
            _this.applyToPay(param)
          } else {
            tool.warning('您取消了')
          }
        }
      })
    } else {
      param.is_wallet = 1;
      _this.applyToPay(param);
    }
  },
  applyToPay: function(param) {
    server.postJSON("/index/Wxpay/index", param, function(res) {
      if (res.data.error != 0) {
        tool.warning(res.data.message);
        return;
      }
      if (res.data.data.order_state == 20 || res.data.data.judge == 1) {
        tool.success('支付成功');
        setTimeout(function() {
          const pages = getCurrentPages();
          wx.switchTab({
            url: '/pages/container/order-list/order-list',
          });
        }, 1000);
        return;
      }
      wx.requestPayment({
        timeStamp: res.data.data.timeStamp,
        nonceStr: res.data.data.nonceStr,
        package: res.data.data.package,
        signType: 'MD5',
        paySign: res.data.data.paySign,
        success: function(r) {
          console.log(r)
          if (r.errMsg == "requestPayment:ok") {
            wx.navigateTo({
              url: '/pages/container/order-details/order-details?all_no=' + param.all_no + "&order_label=" + param.order_label
              // url: '/pages/container/order-list/order-list'
            })
          }
        },
        fail: function(res) {
          tool.warning("支付失败");
        }
      })
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    // 对公、现金弹窗
    this.toCorporate = this.selectComponent("#to-corporate");
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  }
})